package org.jgs1904.rabbitmq.confirm;

import com.rabbitmq.client.Channel;
import org.jgs1904.utils.RabbitMqUtils;

/**
 * @author: 默苍璃
 * @date: 2023-05-31 17:59
 * <p>
 * 批量确认发布
 */
public class Task02 {

    private static final String QUEUE_NAME = "Task02";
    private static final int MESSAGE_COUNT = 1000;

    public static void main(String[] args) throws Exception {

        try (Channel channel = RabbitMqUtils.getChannel();) {

            // 生成一个队列
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);

            //开启发布确认
            channel.confirmSelect();

            //批量确认消息大小
            int batchSize = 100;
            //未确认消息个数
            int outstandingMessageCount = 0;

            long begin = System.currentTimeMillis();
            for (int i = 0; i < MESSAGE_COUNT; i++) {
                String message = i + "";
                channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
                outstandingMessageCount++;
                if (outstandingMessageCount == batchSize) {
                    channel.waitForConfirms();
                    outstandingMessageCount = 0;
                }
            }
            //为了确保还有剩余没有确认消息 再次确认
            if (outstandingMessageCount > 0) {
                channel.waitForConfirms();
            }
            long end = System.currentTimeMillis();
            System.out.println("发布" + MESSAGE_COUNT + "个批量确认消息,耗时" + (end - begin) + "ms");
        }
    }

}
